import { Plugin } from "vite";
import { resolve } from "path";
import fs from "fs";

export default function reloadUnoCSS(): Plugin {
  return {
    name: "vite-plugin-reload-unocss",
    handleHotUpdate({ file, server }) {
      // 监听所有文件变化
      if (file.endsWith(".ts") || file.endsWith(".js") || file.endsWith(".vue") || file.endsWith(".scss")) {
        const unoConfigPath = resolve(__dirname, "uno.config.ts");
        if (fs.existsSync(unoConfigPath)) {
          // 重新加载 uno.config.ts
          delete require.cache[require.resolve(unoConfigPath)];
          const newConfig = require(unoConfigPath).default;

          // 触发热更新
          server.ws.send({
            type: "full-reload",
            path: "*"
          });
        }
      }
    }
  };
}
